package com.ybt.router.tcp.message.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.ybt.router.core.message.IMSDMessage;
import com.ybt.router.tcp.message.TCPMessage;

public class TCPMessageUtil {
    private static Logger logger = Logger.getLogger(TCPMessageUtil.class);

    public static byte[] message2ByteArray(IMSDMessage<byte[]> msg)
            throws Exception {
        if(logger.isDebugEnabled()){
            logger.debug("to serialize the message to byte...");
        }
        //获取报文体长度 
        ByteArrayOutputStream ob = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(ob);
        out.writeObject(msg); //序列化一个会员对象   
        out.close();
        byte[] body = ob.toByteArray();
        
        //拼接报文头
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        ObjectOutputStream outResult = new ObjectOutputStream(result);
        outResult.writeInt(body.length);
        outResult.writeObject(msg);
        outResult.close();
        return result.toByteArray();
    }

    public static TCPMessage byteArray2message(byte[] content)
            throws Exception {
        
        if(logger.isDebugEnabled()){
            logger.debug("to recover the byte to message...");
        }
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(
                content));
        //截取报文头
        int length = in.readInt();
        //返流化报文体
        TCPMessage msg = (TCPMessage) (in.readObject());
        in.close();
        return msg;
    }
    
    public static void main(String[] args){
        try  
        {   
            //创建一个对象输出流，讲对象输出到文件   
            TCPMessage m = new TCPMessage();
            m.setMessage("abc".getBytes("UTF-8"));
            
            Properties header = new Properties();
            header.put("a", "a");
            header.put("b", "b");
            m.setHeader(header);
            m.setMessageID("m1");
            
            byte[] o = TCPMessageUtil.message2ByteArray(m);
            
            //读取UserInfo对象并调用它的toString()方法   
            TCPMessage user=TCPMessageUtil.byteArray2message(o);             
            System.out.println(new String(user.getMessageBody(),"UTF-8"));   
            System.out.println(user.getHeader());   
            System.out.println(user.getMessageID());   
        }   
        catch (Exception x)   
        {   
            x.printStackTrace();   
        }  
    }
}
